package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Author 小坏
 * @Date 2021/1/25 15:00
 * @Version 1.0
 * @program: 父工程 gulimall 万物起源之地
 */

@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("userInfo")
    public String getTokenInfo(@RequestParam("token") String token) {
        String s = redisTemplate.opsForValue().get(token);
        return s;
    }


    @GetMapping("/login.html")
    String loginPage(@RequestParam("redirect_url") String redirect_url, Model model, @CookieValue(value = "sso_token", required = false) String sso_token) {
        if (!StringUtils.isEmpty(sso_token)) {
            //说明之前有人登录过，浏览器留下了痕迹
            return "redirect:" + redirect_url + "?token=" + sso_token;
        }

        model.addAttribute("url", redirect_url);
        return "login";
    }

    @PostMapping("/doLogin")
    String doLogin(@RequestParam("username") String username,
                   @RequestParam("password") String password,
                   @RequestParam("url") String url,
                   HttpServletResponse response) {


        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            //把登录成功的用户保存起来(判断是否登录跳转的=标识)
            String Uid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(Uid, username);
            //把cookie响应到浏览器
            Cookie cookie = new Cookie("sso_token", Uid);
            response.addCookie(cookie);
            //登录成功，跳回之前的页面
            return "redirect:" + url + "?token=" + Uid;
        }
        //登录失败、展示登录页
        return "login";
    }
}
